import tesserocr
from PIL import Image


# 二值化图像, 传入图像和阈值
def binarization(img, threshold):
    img = img.convert('L')
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    return img.point(table, '1')


def convertImage(img):
    # 读取图片并二值化
    image = binarization(img, 120)
    # 转换为带alpha层并旋转
    image2 = image.convert('RGBA').rotate(45, expand=1)
    # 创建一个与旋转图像大小相同的白色图像
    image_fff = Image.new('RGBA', image2.size, (255,) * 4)
    # 使用alpha层的image2作为掩码创建一个复合图像
    return Image.composite(image2, image_fff, image2).convert(image.mode)


def ocrImage(img):
    image = convertImage(img)
    psm = tesserocr.PSM.SINGLE_BLOCK_VERT_TEXT
    code = tesserocr.image_to_text(image, psm=psm)
    return "".join(code.split())[::-1]
